package com.xy.xylive.config;

import cn.hutool.json.JSONUtil;
import com.xy.xylive.api.res.StatRes;
import com.xy.xylive.common.ServiceException;
import com.xy.xylive.domain.Live;
import com.xy.xylive.service.ILiveService;
import com.xy.xylive.xyapi.LiveStatRes;
import com.xy.xylive.xyapi.LiveVideoRes;
import com.xy.xylive.xyapi.LiveVideoV3Api;
import com.xy.xylive.xyapi.LiveVideoV5Api;
import com.xylink.config.SDKConfigMgr;
import com.xylink.util.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Date;
import java.util.List;

@Component
@EnableScheduling // 开启定时任务
@Slf4j
public class ScheduledTask {
    @Autowired
    private ILiveService liveService;

    @Autowired
    private XylinkConf xylinkConf;

    // 定时任务，每隔1分钟执行一次
    // 并同步小鱼直播数据状态 如果到时间了小鱼状态未结束 则不更新为结束
    @Scheduled(fixedRate = 60000)
    public void updateLiveStatus() {
        // 查询直播数据的结束时间小于当前时间的数据 并且本身未结束的数据
        List<Live> liveList = liveService.selectEndList();
        String enterpriseId = xylinkConf.getEnterpriseId();
        LiveVideoV5Api liveVideoV5Api = new LiveVideoV5Api();
        for(Live live : liveList) {
            Result<LiveVideoRes> liveVideoResResult;
            try {
                liveVideoResResult = liveVideoV5Api.getLive(enterpriseId, SDKConfigMgr.getAccessToken(), live.getXyLiveId(), live.getXyMeetingNumber(), live.getPassword());
                if(!liveVideoResResult.isSuccess()) {
                    log.error("小鱼直播查询失败 " + liveVideoResResult.getErrorMsg());
                    // 如果小鱼直播查询失败 则直接更新
                    live.setStatus(3);
                    live.setUpdateTime(new Date());
                    liveService.updateLive(live);
                } else {
                    LiveVideoRes liveVideoRes = liveVideoResResult.getData();
                    if ("END".equals(liveVideoRes.getStatus())) {
                        live.setStatus(3);
                        live.setUpdateTime(new Date());
                        liveService.updateLive(live);
                    }
                }
            } catch (IOException e) {
                log.error("小鱼直播查询接口调用失败 " + JSONUtil.toJsonStr(live), e);
            }
        }
    }

    // 定时任务 每天凌晨4点执行一次
    // 更新直播的统计数据 直播时长以及观看人数
    @Scheduled(cron = "0 0 4 * * ?")
    public void updateLiveStat() {
        Live liveQuery = new Live();
        // 直播结束的直播 不管有没有被删除 进行统计数据获取
        // liveQuery.setIsDelete(0);
        liveQuery.setStatus(3);
        List<Live> liveList = liveService.selectLiveList(liveQuery);
        for(Live live : liveList) {
            if(live.getDuration() != null) {
                continue;
            }
            StatRes statRes = new StatRes();
            statRes.setViewCount(live.getViewCount());
            LiveVideoV3Api liveVideoV3Api = new LiveVideoV3Api();
            Result<LiveStatRes> liveStatResResult;
            try {
                liveStatResResult = liveVideoV3Api.actualDuration(xylinkConf.getEnterpriseId(), SDKConfigMgr.getAccessToken(), live.getXyLiveId());
            } catch (IOException e) {
                log.error("小鱼直播时长查询失败: 直播信息：" + JSONUtil.toJsonStr(live), e);
                continue;
            }
            if(!liveStatResResult.isSuccess()) {
                throw new ServiceException("小鱼直播时长查询失败：" + liveStatResResult.getErrorStatus() + " " + liveStatResResult.getErrorMsg());
            }
            statRes.setDuration(liveStatResResult.getData().getActualDuration());

            // live
            live.setDuration(liveStatResResult.getData().getActualDuration());

            live.setUpdateTime(new Date());
            liveService.updateLive(live);
        }
    }
}
